﻿using G.Net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Douban.API
{
    public class DefaultClient
    {
        public async Task<T> Execute<T>(APIRequest<T> request) where T : APIResponse
        {
            IDictionary<string, string> requestParama = InitialParam<T>(request);

            if (request.RequestMethod == RequestMethod.GET)
            {
                HttpGet get = new HttpGet(APIConfig.BaseUrl + request.Path);

                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debug.WriteLine(APIConfig.BaseUrl  + request.Path);
                }
                foreach (var item in requestParama)
                {
                    get.Params.Add(item.Key, item.Value);
                }
                return DoResponse<T>(await get.RequestAsync(), request);
            }
            return null;
            //else
            //{
            //    HttpPost post = new HttpPost(APIConfig.VANCL_URL + "/" + request.Path);
            //    post.PostData = BuildQuery(requestParama);
            //    if (System.Diagnostics.Debugger.IsAttached)
            //    {
            //        System.Diagnostics.Debug.WriteLine(APIConfig.VANCL_URL + "/" + request.Path);
            //        System.Diagnostics.Debug.WriteLine(post.PostData);
            //    }
            //    return DoResponse<T>(await post.RequestAsync(), request);
            //}
        }
        private T ParseToObj<T>(string body) where T : APIResponse
        {
            T rsp = null;
            try
            {
                rsp = G.Utils.SerializerHelp.JsonDeserialize<T>(body);
                rsp.IsOK = true;
            }
            catch (Exception ex)
            {
                rsp = Activator.CreateInstance<T>();
                rsp.Body = body;
                rsp.ErrorCode = "Json Parse Exception";
                rsp.Title = ex.Message;
            }
            rsp.Body = body;
            return rsp;
        }

        private T DoResponse<T>(RequestResult result, APIRequest<T> request) where T : APIResponse
        {
            Debug.WriteLine(result.Result);

            if (result.Exception == null)
            {
                var obj = ParseToObj<T>(result.Result);
                return obj;
            }
            else
            {
                //if (Debugger.IsAttached)
                //    throw new WebException(result.Result, result.Exception);
                T obj = Activator.CreateInstance<T>();
                obj.Body = result.Result;
                obj.ErrorCode = "Net Exception";
                //由于处于非UI线程，不会出现卡的现象
                if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    obj.Title = "网络故障，请检查您的网络连接是否正常";
                    obj.ErrorCode = "-1";
                }
                else
                    obj.Title = result.Exception.Message;
                return obj;

            }
        }

        private static IDictionary<string, string> InitialParam<T>(APIRequest<T> request) where T : APIResponse
        {
            //用全局参数初始化一个字典集合
            IDictionary<string, string> requestParama = new Dictionary<string, string>();
            var apiParam = request.GetParameters();
            if (apiParam != null)
            {
                foreach (var item in apiParam)
                {
                    if (!string.IsNullOrEmpty(item.Value))
                        requestParama.Add(item.Key, item.Value);
                }
            }
            return requestParama;
        }

    }
}
